package com.taotao.sso.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.taotao.manager.pojo.User;
import com.taotao.sso.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/check/{param}/{type}")
	public ResponseEntity<String> check(@PathVariable(value="param") String param,
			@PathVariable(value="type") Integer type,
			HttpServletRequest request ){
		
		try {
			
			Boolean bool = userService.check(param,type);
			
			// 1 获取callback参数
			String callback = request.getParameter("callback");
			// 如果参数不为空，将返回的数据进行包裹，使用callback
			if(StringUtils.isNotBlank(callback)){
				String result = callback+"("+ bool +")";
				return ResponseEntity.status(HttpStatus.OK).body(result);
			}else{
				return ResponseEntity.status(HttpStatus.OK).body(bool.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
				
	}

	
	// 请求方法 GET
	// URL http://sso.taotao.com/user/{ticket}
	/**
	 * 根据ticket查询用户数据
	 * 
	 * @param ticket
	 * @return
	 */
	@RequestMapping(value = "{ticket}", method = RequestMethod.GET)
	public ResponseEntity<User> queryUserByTicket(@PathVariable("ticket") String ticket) {
		try {
			User user = this.userService.queryUserByTicket(ticket);
			// 判断user是否为空
			if (user != null) {
				// 如果不为空 200
				return ResponseEntity.ok().body(user);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
	}

	
	
}
